import {isNullOrUndefined, strIsEmpty} from "./core";

const filterParserJpaOption=[
    {
        keyword: `NotLike`,
        //true: 如果 searchValue 为空也执行过滤方法(始终匹配成功)
        //默认 false
        forceSearchValueIsEmpty: false,
        filterFun: ({row,propName,searchValue})=>{
            if(strIsEmpty(row[propName])){
                return false
            }
            return !row[propName].includes(searchValue)
        },
    },
    {
        keyword: `Like`,
        filterFun: ({row,propName,searchValue})=>{
            if(strIsEmpty(row[propName])){
                return false
            }
            return row[propName].includes(searchValue)
        },
    }
]


/**
 * 模拟后端sksParams过滤
 * @param list
 * @param queryParams
 * @return {*[]}
 */
export function simulateFilterByQueryParams({list=[],queryParams={},filterFun}={}){
    let {pageNum=1,pageSize=10,sksParams={}}=queryParams
    let tmpPageNum=pageNum-1;
    if(tmpPageNum<0){
        return []
    }
    if(pageSize<=0){
        return []
    }
    let listTmp=list.filter((row)=>{
        //匹配成功的继续往下匹配
        if(!isNullOrUndefined(filterFun)){
            if(!filterFun({row,queryParams})){
                return false
            }
        }
        for (let sksQueryParamName of Object.keys(sksParams)) {
            for (let filterParserJpa of filterParserJpaOption) {
                if (sksQueryParamName.endsWith(filterParserJpa.keyword)) {
                    let propName=sksQueryParamName.substring(0,sksQueryParamName.length-filterParserJpa.keyword.length)
                    let searchValue=sksParams[sksQueryParamName]
                    if(strIsEmpty(searchValue)&&!filterParserJpa.forceSearchValueIsEmpty){
                    }
                    let b = filterParserJpa.filterFun({row,propName,searchValue});
                    // console.log("simulateFilterByQueryParams.filterParserJpa.sksQueryParamName=",sksQueryParamName,"keyword",filterParserJpa.keyword,"row=",row,"propName=",propName,"searchValue=",searchValue,"b=",b)
                    if(!b){
                        return false
                    }
                    break
                }
            }
        }
        return true
    })

    let start=tmpPageNum*pageSize
    let tmp=[]
    for (let i = start; i < listTmp.length; i++) {
        if(i>(start+pageSize)){
            break
        }
        tmp.push(listTmp[i])
    }

    return {
        list: tmp,
        total: listTmp.length
    }
}
